import os
import traceback

import pymysql
import requests

HEADERS = {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive',
           'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)', }

curPath = os.path.dirname(os.path.abspath(__file__))


class mysql:
    def __init__(self, host, database, user, pwd, port=3306, charset='utf8'):
        self.host = host
        self.db = database
        self.user = user
        self.pwd = pwd
        self.port = port
        self.charset = charset

    def getconnect(self):
        if not self.db:
            raise(NameError, "没有设置数据库信息")
        self.conn = pymysql.connect(
            host=self.host, user=self.user, passwd=self.pwd, db=self.db, port=self.port, charset=self.charset)
        cur = self.conn.cursor()
        if not cur:
            raise(NameError, "连接数据库失败")
        else:
            return cur

    def ExecQuery(self, sql):
        """
        执行查询语句
        返回的是一个包含tuple的list，list的元素是记录行，tuple的元素是每行记录的字段
        调用示例：
                ms = mysql(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
                resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
                for (id,NickName) in resList:
                    print str(id),NickName
        """
        cur = self.getconnect()
        cur.execute(sql)
        resList = cur.fetchall()
        self.conn.close()
        return resList

    def ExecNoneQuery(self, sql):
        '''
        执行非查询语句
        '''
        cur = self.getconnect()
        cur.execute(sql)
        self.conn.commit()
        self.conn.close()


def DownCover(id, url):
    r = None
    sMsg = None
    try:
        filename = id + '.jpg'
        url = r"http://221.8.56.50:85" + url
        print('Down: {}, file: {}'.format(url,filename))
        r = requests.get(url, headers=HEADERS, timeout=60)
    except:
        sMsg = traceback.format_exc()

    if sMsg:
        print(sMsg)
        return False

    if not r.status_code == requests.status_codes.codes.ok:
        print("*eCodes 200！")
        return False

    outPath = os.path.join(curPath, 'cover', "{}".format(filename))
    with open(outPath, 'wb') as f:
        f.write(r.content)

    return True


def GetDownList():
    sql = "select id, url from cover where stat = 0 and failcount < 3 limit 1000"
    ms = mysql(host="192.168.0.92", user="root",
               pwd="vipdatacenter", database="ebmbook")
    return ms.ExecQuery(sql)


def main():
    nCount = 0
    while 1:
        tasks = GetDownList()
        if tasks:
            for task in tasks:
                id = task[0]
                url = task[1]
                if True == DownCover(id, url):
                    print('*' * 50)
                    print('下载完成{}'.format(id))
                    nCount += 1
                    print('累计下载{}页'.format(nCount))
                    print('*' * 50 + '\n')
                    sql = "UPDATE cover SET stat = 1 where id = '{}'".format(id)
                else:
                    print('下载{}失败!!'.format(id))
                    sql = "UPDATE cover SET failcount = failcount + 1 where id = '{}'".format(id)
                ms = mysql(host="192.168.0.92", user="root",
                           pwd="vipdatacenter", database="ebmbook")
                ms.ExecNoneQuery(sql)
        else:
            break


if __name__ == '__main__':
    main()
